package com.aiyige.utils.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.widget.TextView;

import com.aiyige.R;

public class LoadingDialog {
    private Dialog dialog;
    private TextView loadText;
    Context context;

    public LoadingDialog(Context context) {
        init(context);
    }

    public LoadingDialog(Context context, String loading) {
        init(context);
        loadText.setText(loading);
    }

    private void init(final Context context) {
        this.context = context;
        dialog = new Dialog(context, R.style.loading_dialog_style);
        dialog.setContentView(R.layout.dialog_loading);
        loadText = (TextView) dialog.findViewById(R.id.loading_tv);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(true);
    }

    public void setCancelable(boolean flag) {
        dialog.setCancelable(flag);
    }

    public void setLoadText(String txt) {
        loadText.setText(txt);
    }

    public void setLoadText(int resId) {
        loadText.setText(resId);
    }

    public void showLoading() {
        if (context != null && !((Activity) context).isFinishing()) {
            dialog.show();
        }
    }


    public void dismiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public Dialog getDialog() {
        return dialog;
    }

    public boolean isShowLoading() {
        return dialog.isShowing();
    }

    public void setCancelListener(OnCancelListener listener) {
        dialog.setOnCancelListener(listener);
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static final class Builder {
        LoadingDialog loadingDialog;

        public Builder() {
        }

        public Builder with(Context context) {
            loadingDialog = new LoadingDialog(context);
            return this;
        }

        public Builder message(int resId) {
            loadingDialog.setLoadText(resId);
            return this;
        }

        public Builder cancelable(boolean cancelable) {
            loadingDialog.setCancelable(cancelable);
            return this;
        }

        public Builder message(String message) {
            loadingDialog.setLoadText(message);
            return this;
        }


        public Builder listener(OnCancelListener listener) {
            loadingDialog.setCancelListener(listener);
            loadingDialog.setCancelable(true);
            return this;
        }

        public LoadingDialog build() {
            return loadingDialog;
        }

        public LoadingDialog show() {
            loadingDialog.showLoading();
            return loadingDialog;
        }
    }
}
